package com.bw.lib_common.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.lib_net.BaseResponse
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * @author ytx
 * @date 2025-09-17 14:45
 * @description 所有viewModel的基类
 */
open class BaseViewModel:ViewModel() {

    //对流统一处理
    fun <M:BaseResponse<T>,T> execute(
        action:Flow<M>,
        onStart:(suspend ()-> Unit)? = null,
        onError:(suspend (String)-> Unit)? = null,
        onFinish:(suspend (M)-> Unit)? = null
    ) = viewModelScope.launch {
        action.onStart {
            onStart?.invoke()
        }.catch {
            onError?.invoke(it.message?:"未知错误")
        }.collectLatest{//只收集最近数据，丢弃旧数据，解决背压问题
            if (it.code == 200){
                onFinish?.invoke(it)
            }else{
                onError?.invoke(it.msg?:"未知错误")
            }
        }

    }


}